package win.bitterwine.filter;

import org.smart4j.framework.util.CollectionUtil;
import win.bitterwine.specialBean.ModuleBean;

import java.util.List;

/**
 * 验证用户权限工具类
 * Created by Administrator on 2017/6/19.
 */
public class Authority {
    private  List<ModuleBean> list;
    private String currentURL;

    /**
     * @param currentURL 当前请求的url
     * @param list 当前用户所拥有的模块的集合
     */
    public Authority(String currentURL, List<ModuleBean> list) {
        this.list = list;
        this.currentURL = currentURL;
    }

    /**
     * 判断当前用户是否有访问该路径的权限,是否合法
     * @return
     */
    public boolean isLegal(){
        if(CollectionUtil.isEmpty(list))
            return false;
        for(ModuleBean mb : list){
            if(isMatches(currentURL,mb.getPath()))
                return true;
        }
        return false;
    }

    /**
     * 根据数据库中通配符的表示来验证当前的url是否符合规则
     * @param str
     * @param myReg
     * @return
     */
    private boolean isMatches(String str, String myReg){
        String temp;
        if(!myReg.contains("*")) {
            if (myReg.equals(str))
                return true;
            return false;
        }
        if(myReg.indexOf("*") != myReg.length()-1)
            return false;
        temp = myReg.substring(0,myReg.length()-1);
        if(temp.endsWith("/"))
            temp = temp.substring(0,temp.length()-1);
        if(myReg.substring(0,myReg.length()-1).contains("*"))
            return false;
        if(str.startsWith(temp))
            return true;
        return false;
    }


    public static void main(String[] args) {
        String reg = "/aaa/bbb/sss/*";
        String str = "/aaa/bbb/sss/gfhfghfghf";
        //System.out.println(isMatches(str,reg));
    }

}
